package cn.liujianlin.qrcode.controller;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Controller
public class QrcodeController {
    @ResponseBody
    @GetMapping("/decodeQrcode")
    public cn.liujianlin.qrcode.entity.Result decodeQrcode(String imageUrl){
        cn.liujianlin.qrcode.entity.Result apiResult = new cn.liujianlin.qrcode.entity.Result();
        if(imageUrl.equals("")){
           apiResult.setCode(100);
           apiResult.setData("");
           apiResult.setMsg("参数错误");
        }else{
            BufferedImage image;
            HttpURLConnection conn = null;
            try {
                URL url = new URL(imageUrl);
                conn = (HttpURLConnection) url.openConnection();
                //设置超时间为3秒
                conn.setConnectTimeout(3*1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                InputStream inputStream = conn.getInputStream();

                image = ImageIO.read(inputStream);
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                //精度
                hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
                //复杂模式
                hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);

                Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
                System.out.println("result:"+result);
                apiResult.setCode(200);
                apiResult.setData(result.getText());
                apiResult.setMsg("成功");
            } catch (IOException e) {
                e.printStackTrace();
                apiResult.setCode(101);
                apiResult.setMsg(e.getMessage());
            } catch (NotFoundException e) {
                e.printStackTrace();
                apiResult.setCode(101);
                apiResult.setMsg(e.getMessage());
            }finally {

            }
        }

        return  apiResult;
    }
}
